package com.qipay.admin.withdraw.service;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Holiday;
import com.qipay.mapper.HolidayMapper;
import com.qipay.utils.DateUtils;
import com.qipay.utils.HttpClientUtils;
import com.qipay.utils.MD5Util;
import com.qipay.utils.RSAUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * 代付的逻辑
 */
@Service
public class WithdrawAnother2Service {
    private static Logger logger = LoggerFactory.getLogger(WithdrawAnother2Service.class);


    @Autowired
    HolidayMapper holidayMapper;
    /**
     *  八维码代付接口，请求代付（管理员提现）
     * @return
     * @throws UnsupportedEncodingException
     */
    @Transactional
    public Map<String,Object> anotherApply(String customerNo,String pubkey,Map<String, Object> params) throws Exception {
        logger.info("进入代付请求");
        String requertStr=createRetStr(params);
        String reqStr = RSAUtils.encryptByPublicKey(requertStr.getBytes("UTF-8"), pubkey);
        Map<String, Object> paramsStr = new HashMap<>();
        paramsStr.put("customerNo",customerNo);
        paramsStr.put("cipher_data", URLEncoder.encode(reqStr));
        String returnStr=http("http://df.uranuspay.com/checkAccount/payOther.action",paramsStr);
        logger.info("进入代付请求");
        //--------插入日志
        Holiday reqLog = new Holiday();
        reqLog.setDate(requertStr);//请求报文
        reqLog.setIsHoliday((byte)2);//请求类型，1表示查询,2表示代付
        reqLog.setName(returnStr);//响应报文
        holidayMapper.insert(reqLog);
        //---------日志结束
        logger.info("代付请求返回报文"+returnStr);
        JSONObject res=JSONObject.parseObject(returnStr);
        Map<String, Object> returnParams = new HashMap<>();
        if(res.getString("retcode").equals("0000")) {
            returnParams.put("retcode", "0000");
            return returnParams;
        }
        returnParams.put("retcode", "9999");
        returnParams.put("retmsg", res.get("retmsg"));
        return returnParams;
    }

    /**
     * 乐娱--查询余额
     * @param
     * @return
     */
    public Map<String, Object> findDfBalance(String customerNo,String key,String pubkey) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("transCode","008");
        String date= DateUtils.sdf14.format(new Date());
        params.put("reqTime",date.substring(8,date.length()));
        params.put("customerNo",customerNo);//扫码小额
        String sign = MD5Util.getSign(params,key).toUpperCase();
        params.put("sign",sign);
        String requertStr=createRetStr(params);
        String reqStr = RSAUtils.encryptByPublicKey(requertStr.getBytes("UTF-8"), pubkey);
        Map<String, Object> paramsStr = new HashMap<>();
        paramsStr.put("customerNo",customerNo);
        paramsStr.put("cipher_data", URLEncoder.encode(reqStr));
        String returnStr=http("http://df.uranuspay.com/checkAccount/queryDfBalance.action",paramsStr);
        JSONObject res=JSONObject.parseObject(returnStr);
        logger.info("代付余额查询请求返回报文"+returnStr);
        Map<String, Object> returnParams = new HashMap<>();
        if(res.getString("retcode").equals("0000")) {
            returnParams.put("balance", res.get("balance"));
            returnParams.put("retcode", "0000");
            return returnParams;
        }
        returnParams.put("retcode", "9999");
        returnParams.put("retmsg", res.get("retmsg"));
        return returnParams;
    }

    public static String createRetStr(Map<String, Object> packageParams) {
        StringBuffer sb = new StringBuffer();
        Set<?> es = packageParams.entrySet();
        Iterator<?> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = String.valueOf( entry.getValue());
            if (null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
        String sss=sb.toString().substring(sb.toString().length()-1, sb.toString().length());
        if (sss.equals("&")) {
            sss=sb.toString().substring(0, sb.toString().length()-1);
        }
        return sss;

    }

    //发送请求
    public static String http(String url, Map<String, Object> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        String sbStr="";
        if (params != null) {
            for (Map.Entry<String, Object> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sbStr=sb.substring(0, sb.length() - 1);
        }
        System.out.println("send_url:" + url);
        System.out.println("send_data:" + sbStr);
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sbStr);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }
    /**
     * 拼接字符串
     * @param maps
     * @return
     */
    public String generateStr(Map<String,Object>maps){
        SortedMap<String, Object> params=new TreeMap<String, Object>();
        for (String mapKey : maps.keySet()) {
            params.put(mapKey, maps.get(mapKey));
        }

        StringBuilder sb=new StringBuilder();
        for (String keyItem : params.keySet()) {
            if(params.get(keyItem)!=null&&!params.get(keyItem).toString().equals("")
                    &&!keyItem.equals("sign")&&!keyItem.equals("Sign")&&
                    !keyItem.equals("signature")&&!keyItem.equals("signData")){
                sb.append(params.get(keyItem).toString());
            }
        }
        String bunch=sb.toString();
        return bunch;
    }
    @Transactional
    public Map<String,Object> anotherApply1(Map<String, Object> params) throws Exception {
        String apiUrl = "http://172.96.202.226:48004/api/pay/transferMoney";
        String userId = "M000088";
        String key = "9768dcda8a874d0fa86f46426e09b3ef";

        params.put("userId",userId);
        params.put("callBackUrl", "http://manager.ws-pay.com/callback/v1/uspay/quickin");
        params.put("timestamp", Long.valueOf(DateUtils.sdf14.format(new Date())));
        String sign = MD5Util.getSign(params,key).toLowerCase();
        params.put("sign",sign);

        String result = HttpClientUtils.sendPostJson(params,apiUrl);

        //--------插入日志
        Holiday reqLog = new Holiday();
        reqLog.setDate(params.toString());//请求报文
        reqLog.setIsHoliday((byte)2);//请求类型，1表示查询,2表示代付
        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        //---------日志结束
        Map<String, Object> returnParams = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if("200".equals(jsonObject.getString("resCode"))){
            returnParams.put("retcode", "0000");
            return returnParams;
        }else{
            returnParams.put("retcode", "9999");
            returnParams.put("retmsg", jsonObject.getString("resMsg"));
        }

        return returnParams;
    }


}
